package com.xxx.config;


import com.xxx.pojo.Employee;
import com.xxx.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

@Slf4j
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private EmployeeService employeeService;


    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        log.info("通过授权过滤器");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        Subject subject = SecurityUtils.getSubject();
        Employee employee = (Employee) subject.getPrincipal();

        info.addRole(employee.getRole());
        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        log.info("通过认证过滤器");

        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;

        Employee employee = employeeService.okLogin(token.getUsername());
        log.info("employee:{}",employee);

        if (employee == null){
            return null;
        }

        /**
         * 1.principal 用户资源，可以在SecurityUtils取出来
         * 2.credentials 等待验证的密码
         * 3.realmName 盐，默认空“”
         */
        return new SimpleAuthenticationInfo(employee,employee.getPassword(),"");
    }
}
